#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import struct
import time

def get_info_from_raw(json_str,topic_ip):
    # for line in json_str:
    #     if line:
    #         # 分割字符串获取各个部分
    #         parts = line.split('@')
    #         time_str = parts[0]
    #         type_str = parts[1]  # E1, 其中'E'可能是固定的，数字代表类型
    #         ip_address = parts[2].strip('*')  # 去除可能存在的星号
    #         # if ip_address != "10.143.187.144":
    #         #     continue
    #         json_str = parts[3]
    #         try:
    #             json_str = json.loads(json_str)
    #         except:
    #             print("ERROR:JSON_LOAD")
    
    int_byte_list = [int(byte) for byte in json_str]
    # 将每个元素转换为16进制，并格式化输出（如果需要）
    hex_list = [hex(byte & 0xFF).zfill(2).upper() for byte in int_byte_list]
    int_byte_list1 = [int(byte.strip(), 16) for byte in hex_list]
    length = (int_byte_list1[3] << 8) | int_byte_list1[2]
    # logger.info(f"报文长度为:{length}真值:{len(int_byte_list)}")
    type = (int_byte_list1[5] << 8) | int_byte_list1[4]
    result = []
    # logger.info(f"报文类型为:{type}")
    if type == 2002:
        return []
        # logger.info(f"心跳报文")
    elif type == 2004:
        # logger.info(f"跟踪报文")
        # print(int_byte_list1[6],int_byte_list[6])
        time_raw = f"{int_byte_list1[6] + 2000}-{int_byte_list1[7]}-{int_byte_list1[8]}-{int_byte_list1[9]}-{int_byte_list1[10]}-{int_byte_list1[11]}-{(int_byte_list1[13] << 8) | int_byte_list1[12]}"
        frame_num = (int_byte_list1[15] << 8) | int_byte_list1[14]
        target_num = (int_byte_list1[17] << 8) | int_byte_list1[16]
        # logger.info(f"时间:{time_raw} 帧号:{frame_num} 目标总数:{target_num}")
        timestamp = time.time()
        # 多个目标需要循环遍历
        count = 0
        index = 18 + count * 37
        while index + 37 < length:
            id = (int_byte_list1[index + 1] << 8) | int_byte_list1[index]
            XDEC = (int_byte_list1[index + 3] << 8) | int_byte_list1[index + 2]
            X = (XDEC - 32768) / 100
            YDEC = (int_byte_list1[index + 5] << 8) | int_byte_list1[index + 4]
            Y = YDEC / 20
            ADEC = (int_byte_list1[index + 7] << 8) | int_byte_list1[index + 6]
            A = ADEC / 100
            VDEC = (int_byte_list1[index + 9] << 8) | int_byte_list1[index + 8]
            Vx = (VDEC - 32768) / 100
            VDEC = (int_byte_list1[index + 11] << 8) | int_byte_list1[index + 10]
            Vy = (VDEC - 32768) / 100
            ADEC = (int_byte_list1[index + 13] << 8) | int_byte_list1[index + 12]
            Ax = (ADEC - 32768) / 100
            ADEC = (int_byte_list1[index + 14] << 8) | int_byte_list1[index + 14]
            Ay = (ADEC - 32768) / 100
            default = int_byte_list1[index + 16]
            # 将整数列表转换为字节串
            byte_data_lon = bytes(int_byte_list1[index + 17:index + 25])
            # 使用 struct.unpack 解析字节串为 double 类型
            lon, = struct.unpack('<d', byte_data_lon)  # '>d' 表示大端序的双精度浮点数
            default = int_byte_list1[index + 25]
            default = int_byte_list1[index + 26]
            # 将整数列表转换为字节串
            byte_data_lat = bytes(int_byte_list1[index + 27:index + 35])
            # 使用 struct.unpack 解析字节串为 double 类型
            lat, = struct.unpack('<d', byte_data_lat)  # '>d' 表示大端序的双精度浮点数
            laneNum = int_byte_list1[index + 35]
            end = int_byte_list1[index + 36]
            result.append([frame_num,target_num,id,A,laneNum,lat,lon,Ax,X,Vx,Ay,Y,Vy,timestamp,topic_ip])
            # logger.info(
            #     f"id:{id} X:{X} Y:{Y} A:{A} Vx:{Vx} Vy{Vy} Ax:{Ax} Ay:{Ay} lon:{lon} lat:{lat} lane:{laneNum}")
            count += 1
            index = 18 + count * 37
        return  result
    else:
        return []
        

# file_path = r"C:/Users/Liu Yi/Downloads/test_json_DataLog"
# with open(file_path, 'r', encoding='utf-8') as f:
#     while True:
#         json_str = f
#         csv_output = io.StringIO()
#         fieldnames = ['frameNo', 'targetNum', 'targetId', 'angle', 'laneNo', 'latitude', 'longitude', 
#                 'xAcceleration', 'xCoordinate', 'xVelocity', 'yAcceleration', 
#                 'yCoordinate', 'yVelocity', 'timestamp','IP']
#         csv_writer = csv.DictWriter(csv_output, fieldnames=fieldnames)
#         csv_writer.writeheader()
#         csv_data = get_info_from_raw(json_str,csv_writer,1)
#         print(csv_data.getvalue())

